const Base = require('../../base.js');
const ThinkJS = require('thinkjs');

module.exports = class extends Base {
  async indexAction() {
    let data = this.post()
    // 0.手机号是否存在
    let user = await this.model('user/index').phone(data.phone)
    if (!user) {
      return this.fail(-1, '手机号不存在')
    }

    // 1.判断是否获取验证码
    let sms_code = await this.session('sms_code')
    
    if (!sms_code) {
      return this.fail(-1, '请先获取验证码')
    }
    console.log('已获取验证码')
    // 2.判断验证码是否过期
    if (sms_code.time < Date.now()) {
      return this.fail(-1, '验证码已失效')
    }
    console.log('验证码未失效')
    // 3.判断验证码 手机号是否正确
    if (data.phone != sms_code.phone || data.code != sms_code.code) {
      return this.fail(-1, '验证码不正确')
    }

    // 4.判断密码是否输入正确
    if (!data.password || data.password != data.password2) {
      return this.fail(-1, '两次密码不一致')
    }

    try {
      await this.model('user/index').edit({
        _id: user._id,
        password: think.encodePwd(data.password)
      })
      this.json({
        status: 200, message: 'success'
      })
    } catch (err) {
      this.fail(-1, err.message)
    }
  }
};
